﻿//--------------------------------------------------------------------------------------------------------------
// <copyright file="CSPCivilServantMyCasesWUC.cs" company="Microsoft Corporation" author="David Martos" date="01/01/2008">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Security;
using System.Xml.Serialization;
using Microsoft.Security.Application;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;


namespace CSP.WebParts.UserControls
{

    /// <summary>
    /// Shows a list of the civil servant cases
    /// </summary>  
    public class CSPCivilServantMyCasesWUC : CSPBaseWUC
    {      

        #region Members
        protected GridView gvCivilServantMyCases;
        protected Label lblError;
        #endregion

        #region Properties
        public string CaseDetailsURL { get; set; }
        public bool OpenCaseInNewWindow { get; set; }      
        public int PageSize { get; set; }
        #endregion


        #region PageEvents
        /// <summary>
        /// Fired on page load
        /// </summary>  
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            try
            {
                LoadData();
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCivilServantMyCasesLoadErrorMessage), this.GetType().Name, ex);
            }
        }

        /// <summary>
        /// Fired on page create child controls
        /// </summary>  
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                gvCivilServantMyCases.PageIndexChanging += new GridViewPageEventHandler(gvCivilServantMyCases_PageIndexChanged);
                gvCivilServantMyCases.Sorting += new GridViewSortEventHandler(gvCivilServantMyCases_SortCommand);
                if (this.PageSize != 0)
                    gvCivilServantMyCases.PageSize = this.PageSize;              
            }           
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCivilServantMyCasesCreateChildErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }
        #endregion


        #region Methods
        /// <summary>
        /// Gets the list of cases assigned to the current civil servant
        /// </summary>  
        protected void LoadData()
        {
            MembershipInterface.MembershipServiceClient client = null;
            CSP.MembershipInterface.ObjectModel.Case[] cases = new CSP.MembershipInterface.ObjectModel.Case[0];

            try
            {
                client = new CSP.MembershipInterface.MembershipServiceClient();
                              
                if (Context.Request.QueryString["CaseTypeID"] != null)
                    cases = client.GetCasesByCaseType(client.GetCaseTypeByName (Context.Request.QueryString["CaseTypeID"]));//GetCaseType(client,Convert.ToInt32 (Context.Request.QueryString["CaseTypeID"])));//((CSP.MembershipInterface.ObjectModel.CaseType)Enum.Parse(typeof(CSP.MembershipInterface.ObjectModel.CaseType), Context.Request.QueryString["CaseTypeID"].ToString()));
                else
                    cases = client.GetCases();
                
          
                // Now, convert the cases to rows in a DataTable for display
                DataTable casesTable = new DataTable();
                casesTable.Columns.Add("CaseID", typeof(string));
                casesTable.Columns.Add("Title", typeof(string));
                casesTable.Columns.Add("Description", typeof(string));
                casesTable.Columns.Add("CaseStatusTitle", typeof(string));
                casesTable.Columns.Add("DueDate", typeof(DateTime));
                casesTable.Columns.Add("CaseTypeTitle", typeof(string));
                casesTable.Columns.Add("CaseTypeID", typeof(string));

                foreach (CSP.MembershipInterface.ObjectModel.Case crmCase in cases)
                {                       
                    string destinationurl = string.Format("<a href=\"{0}?id={3}\" title=\"\" {2}>{1}</a>", AntiXss.HtmlAttributeEncode(this.CaseDetailsURL), AntiXss.HtmlAttributeEncode(crmCase.Title), OpenCaseInNewWindow ? "target=\"_blank\"" : "", AntiXss.UrlEncode(crmCase.ID));
                    casesTable.Rows.Add(new object[] { destinationurl, crmCase.Title, crmCase.Description, crmCase.Status.CaseStatusTitle, crmCase.DueDate, crmCase.Type.CaseTypeTitle, crmCase.Type.CaseTypeId });
                }

                DataView dataView = casesTable.DefaultView;

                if (ViewState["SortExp"] != null && ViewState["SortDir"] != null)
                {
                    dataView.Sort = ViewState["SortExp"] + " " + ViewState["SortDir"];
                }

              
                this.gvCivilServantMyCases.DataSource = dataView.ToTable ();
                this.gvCivilServantMyCases.DataBind();                                                                  
            }           
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPLoadControlErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
            finally
            {
                if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                    client.Close();
            }
            if (cases == null || cases.Length == 0)
            {
                this.gvCivilServantMyCases.Visible = false;
                WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPEmptyListMessage));
            }           
        }

        private CSP.MembershipInterface.ObjectModel.CaseType GetCaseType(CSP.MembershipInterface.MembershipServiceClient client,int idType) {
            CSP.MembershipInterface.ObjectModel.CaseType ct = new CSP.MembershipInterface.ObjectModel.CaseType();
            CSP.MembershipInterface.ObjectModel.CaseType[] ctAll;

            ctAll = client.GetCaseTypes();
            foreach (CSP.MembershipInterface.ObjectModel.CaseType caseType in ctAll)
            {
                if (caseType.CaseTypeId == idType)
                {
                    ct = caseType;
                    break;
                }
            }

            return ct;
        }
        #endregion
       

        #region ControlEvents 
        /// <summary>
        /// Fired on gridview sorting
        /// </summary>     
        protected void gvCivilServantMyCases_SortCommand(object sender, GridViewSortEventArgs e)
        {
            try
            {
                base.GridViewSortCommand(((GridView)sender), e);                    
            }           
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCivilServantMyCasesSortingErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }

        /// <summary>
        /// Fired on gridview paging
        /// </summary>  
        protected void gvCivilServantMyCases_PageIndexChanged(object sender, GridViewPageEventArgs e)
        {
            try
            {
                base.GridViewPageChangedCommand(((GridView)sender), e);
            }          
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPCivilServantMyCasesPagingErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }                  
        #endregion
    }
}
